package com.ecar.api.service.passenger.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ecar.api.service.common.DictionaryService;
import com.ecar.api.service.common.impl.DictionaryServiceImpl;
import com.ecar.api.service.driver.DriverService;
import com.ecar.api.service.order.OrderService;
import com.ecar.api.service.passenger.PassengerOrderService;
import com.ecar.api.support.dto.Constants;
import com.ecar.api.support.dto.order.DriverWilddogDto;
import com.ecar.api.support.util.DateUtil;
import com.ecar.api.support.util.OrderUtil;
import com.ecar.api.support.util.RandomUtil;
import com.ecar.api.support.util.Redis;
import com.ecar.api.support.util.UserUtil;
import com.ecar.api.support.util.UuidUtils;
import com.ecar.api.support.util.WilddogUtil;
import com.ecar.common.dto.DataBean;
import com.ecar.common.util.BeanUtils;
import com.ecar.common.util.DataValidateUtil;
import com.ecar.common.util.StringUtil;
import com.ecar.core.common.dao.DictionaryMapper;
import com.ecar.core.common.entity.User;
import com.ecar.core.driver.dao.CarMapper;
import com.ecar.core.driver.dao.ModelSetMapper;
import com.ecar.core.driver.entity.Car;
import com.ecar.core.driver.entity.Driver;
import com.ecar.core.order.dao.OrderMapper;
import com.ecar.core.order.dao.OrderPriceDetailMapper;
import com.ecar.core.order.entity.Order;
import com.ecar.core.order.entity.OrderPriceDetail;
import com.esotericsoftware.minlog.Log;

import net.sf.json.JSONObject;

@Service
@Transactional
public class PassengerOrderServiceImpl implements PassengerOrderService {
	@Autowired
	DictionaryService dictionaryService;

	@Autowired
	OrderMapper orderMapper;

	@Autowired
	OrderService orderService;

	@Autowired
	DriverService driverService;

	@Autowired
	ModelSetMapper modelSetMapper;

	@Autowired
	CarMapper carMapper;

	@Autowired
	OrderPriceDetailMapper orderPriceDetailMapper;

	/**
	 * 
	 * @Title:接口
	 * @Description:快车订单列表查询
	 * @author paul
	 * @date 2017年10月30日上午11:26:37
	 * @param param
	 *            接口参数
	 * @return
	 */
	@Override
	public List<Order> getAllOrderListByQueryF(Map<String, Object> param) {
		List<Integer> list = new ArrayList<>();
		// list.add(Constants.FAST_NOW);
		// list.add(Constants.FAST_FUTURE);
		list.add(Constants.CARPOOL_NOW);
		list.add(Constants.CARPOOL_FU);
		param.put("type", list);
		return orderMapper.getOrderListByQuery(param);
	}

	@Override
	public List<Order> getAllOrderListByQueryJS(Map<String, Object> param) {
		List<Integer> list = new ArrayList<>();
		// list.add(Constants.RECEIVE_TYPE);
		// list.add(Constants.SEND_TYPE);
		list.add(Constants.FAST_NOW);
		list.add(Constants.FAST_FUTURE);
		param.put("type", list);
		return orderMapper.getOrderListByQuery(param);
	}

	@Override
	public List<Order> getAllOrderListByQueryJS2(Map<String, Object> param) {
		List<Integer> list = new ArrayList<>();
		list.add(Constants.RECEIVE_TYPE);
		list.add(Constants.SEND_TYPE);
		// list.add(Constants.FAST_NOW);
		// list.add(Constants.FAST_FUTURE);
		param.put("type", list);
		return orderMapper.getOrderListByQuery(param);
	}

	/**
	 * 匿名乘客下单创建订单
	 * 
	 * @param 下单参数
	 * @return 操作结果
	 * @author fire
	 * 
	 */
	@Override
	public DataBean createF2FOrder(Order order) {
		order.setId(UuidUtils.getUUID());
		// 网约车生成的订单以wy开头
		String orderNo = "20" + RandomUtil.getRandomDateAndNumber();
		order.setOrderNum(orderNo);
		order.setOrderType(6);
		order.setPayStatus(1);
		order.setOrderStatus(Constants.START_ROAD);
		order.setCreateTime(new Date());
		order.setReceiveTime(new Date());
		order.setStartTime(new Date());
		order.setPlanTime(new Date());

		List<Order> temp = orderService.selectF2FParentOrder(order.getDriverId());
		if (temp.size() == 0) {
			order.setParentOrder(order.getOrderNum());
		} else {
			order.setParentOrder(temp.get(0).getParentOrder());
			int tempSeat = 0;
			for (Order a : temp) {
				tempSeat = tempSeat + a.getUseSeats();
			}
			Car car = carMapper.selectByDriverId(order.getDriverId());
			Integer useSeat = tempSeat;
			Integer leftSeat = 0;
			if (car.getSeatType() == 1) {
				// 5座
				leftSeat = 4 - useSeat;
			} else if (car.getSeatType() == 2) {
				// 7座
				leftSeat = 5 - useSeat;
			}
			if (leftSeat < order.getUseSeats()) {
				return new DataBean(500, new JSONObject(), "超载");
			}
		}
		int pk = orderMapper.insertSelective(order);
		if (pk < 1) {
			return new DataBean(500, new JSONObject(), "下单失败");
		}
		modelSetMapper.stopGetOrder(order.getDriverId());

		/*
		 * DriverWilddogDto driverWilddogDto=new DriverWilddogDto();
		 * BeanUtils.copySolidProperties(order, driverWilddogDto);
		 * driverWilddogDto.setCreateTime(DateUtil.dateToMS(order.getStartTime()
		 * )); driverWilddogDto.setCarpool(orderNo);
		 * driverWilddogDto.setPassengerName(order.getPassengerPhone());
		 * driverWilddogDto.setPhone(order.getPassengerPhone());
		 * driverWilddogDto.setPassengerId(order.getPassengerId());
		 * 
		 * Map<String, Object>
		 * map=DataValidateUtil.objectToMap(DataValidateUtil.parseNull(
		 * driverWilddogDto)); HashMap<String, Object> tempMap = new
		 * HashMap<String, Object>(); tempMap.put(order.getOrderNum(), map);
		 * 
		 * WilddogUtil.sendNowOrderToDriver(order.getDriverId(), tempMap);
		 * 
		 * List<Order>
		 * orders=orderService.selectOrderByParentOrder(order.getParentOrder());
		 * OrderUtil.sortOrder(orders);
		 */

		return new DataBean(200, order, "下单成功");
	}

	/**
	 * 乘客端下单接口
	 * 
	 * @param 下单参数
	 * @return 操作结果
	 * @author 涂许平
	 * 
	 * @changer fire 添加了派单的过程
	 */

	@Override
	public DataBean createOrder(JSONObject fields) {
		Order order = new Order();
		long createTime = System.currentTimeMillis();
		order.setCreateTime(new Date(createTime));
		// 网约车生成的订单以20开头
		String orderNo = "20" + RandomUtil.getRandomDateAndNumber();
		try {
			int passengerId = fields.getInt("passengerId");

			// 判断乘客是否有未支付的订单
			int count1 = orderMapper.selectPayOrderCountByPassengerId(passengerId);
			if (count1 > 0) {
				return new DataBean(408, new JSONObject(), "乘客有未支付订单,请先完成支付后再下单!");
			}

			String planTime = fields.getString("planTime");
			if (StringUtil.isEmpty(planTime)) {
				order.setPlanTime(new Date(createTime));
				order.setStartTime(new Date(createTime));

			} else {
				long l = Long.valueOf(planTime);
				if (l < createTime) {
					return new DataBean(407, new JSONObject(), "预约时间不能早于下单时间!");
				}
				Date date = new Date(l);
				order.setPlanTime(date);
				order.setStartTime(date);
			}

			// 根据乘客id查询客户未完成的订单数
			List<Order> list = orderMapper.selectOrderCountByPassengerId(passengerId);
			int a = 0;
			if (!list.isEmpty()) {
				for (Order order1 : list) {
					long planTime1 = order1.getPlanTime().getTime();
					long createTime2 = order1.getCreateTime().getTime();

					if (planTime1 == createTime2 && StringUtil.isEmpty(planTime)) {
						return new DataBean(407, new JSONObject(), "乘客有正在进行的专车或接送机实时单,不能重复下单!");
					}

					if (planTime1 != createTime2) {
						a++;
					}

				}
			}

			if (a > 0 && !StringUtil.isEmpty(planTime)) {
				return new DataBean(407, new JSONObject(), "乘客不能多次下预约单!");
			}

			String id = UuidUtils.getUUID();
			order.setId(id);
			order.setOrderNum(orderNo);

			String flightId = fields.getString("flightId");
			if (StringUtil.isEmpty(flightId)) {
				flightId = null;
			}
			order.setFlightId(flightId);

			int useSeats = fields.getInt("useSeats");
			order.setUseSeats(useSeats);

			int carType = fields.getInt("carType");
			order.setCarType(carType);

			// 乘车人姓名
			String customerName = fields.getString("customerName");
			if (StringUtil.isEmpty(customerName)) {
				customerName = null;
			}
			order.setCustomerName(customerName);

			// 乘车人电话
			String customerPhone = fields.getString("customerPhone");
			if (StringUtil.isEmpty(customerPhone)) {
				customerPhone = null;
			}
			order.setCustomerPhone(customerPhone);

			String startAddress = fields.getString("startAddress");
			if (StringUtil.isEmpty(startAddress)) {
				return new DataBean(10010, new JSONObject(), "起点地址不能为空,请返回选择!");
			}
			order.setStartAddress(startAddress);

			String startLocation = fields.getString("startLocation");
			if (StringUtil.isEmpty(startLocation)) {
				return new DataBean(10011, new JSONObject(), "起点经纬度不能为空,请返回选择!");
			}
			order.setStartLocation(startLocation);

			String desAddress = fields.getString("desAddress");
			if (StringUtil.isEmpty(desAddress)) {
				return new DataBean(10012, new JSONObject(), "终点地址不能为空,请返回选择!");
			}
			order.setDesAddress(desAddress);

			String desLocation = fields.getString("desLocation");
			if (StringUtil.isEmpty(desLocation)) {
				return new DataBean(10013, new JSONObject(), "终点经纬度不能为空,请返回选择!");
			}
			order.setDesLocation(desLocation);

			int orderType = fields.getInt("orderType");
			order.setOrderType(orderType);
			order.setPassengerId(passengerId);
			/*
			 * if (i<0||i>10) { return new DataBean(405, new JSONObject(),
			 * "订单类型错误!"); }
			 */
			// 判断订单类型
			if (Constants.FAST_NOW == orderType) {
				order.setStartTime(new Date());
			}

			// 在订单类型为5拼车的时候,判断redis里面有没有存好的一口价
			if (Constants.CARPOOL_NOW == orderType) {

				int wait = fields.getInt("canWait");
				if (wait != 0 && wait != 1) {
					return new DataBean(406, new JSONObject(), "请正确传参乘客是否愿意等待参数!");
				}
				order.setWait(wait);

				String string = Redis.c.get(Redis.K.CARPOOL_INFO.to(passengerId));

				if (StringUtil.isNotEmpty(string)) {
					JSONObject fromObject = JSONObject.fromObject(string);

					Double spassRatePrice = Double.valueOf(fromObject.get("spassRatePrice").toString());
					Double fpassRatePrice = Double.valueOf(fromObject.get("fpassRatePrice").toString());

					// 愿意等的优惠暂时没有插入价格详情表
					Double canWait = Double.valueOf(fromObject.get("canWait").toString());
					Double minPrice = Double.valueOf(fromObject.get("minPrice").toString());
					Double sprePrice = Double.valueOf(fromObject.get("sprePrice").toString());
					Double fprePrice = Double.valueOf(fromObject.get("fprePrice").toString());
					Double snightMoney = Double.valueOf(fromObject.get("snightMoney").toString());
					Double fnightMoney = Double.valueOf(fromObject.get("fnightMoney").toString());
					Double distance = Double.valueOf(fromObject.get("distance").toString());

					OrderPriceDetail detail1 = new OrderPriceDetail();
					OrderPriceDetail detail2 = new OrderPriceDetail();
					String uuid = UuidUtils.getUUID();
					// 拼车失败
					detail1.setSuccess(0);
					detail1.setId(uuid);
					detail1.setOrderNum(orderNo);
					detail1.setOverMileagePrice(fpassRatePrice);
					detail1.setBasePrice(minPrice);
					detail1.setLightDriverPrice(fnightMoney);
					detail1.setRoadDistance(distance);
					detail1.setPassengerId(String.valueOf(passengerId));
					// 当乘客愿意等的时候,一口价要减去愿意等的价钱
					if (wait == 1) {
						detail1.setTotalPrice(fprePrice - canWait);
						detail2.setTotalPrice(sprePrice - canWait);
					} else {
						// 不愿意等的时候
						detail1.setTotalPrice(fprePrice);
						detail2.setTotalPrice(sprePrice);
					}
					Log.info("成功预估价=============================" + sprePrice);
					Log.info("失败预估价=============================" + fprePrice);
					String uuid2 = UuidUtils.getUUID();
					// 拼车成功
					detail2.setSuccess(1);
					detail2.setId(uuid2);
					detail2.setOrderNum(orderNo);
					detail2.setOverMileagePrice(spassRatePrice);
					detail2.setBasePrice(minPrice);
					detail2.setLightDriverPrice(snightMoney);
					detail2.setRoadDistance(distance);
					detail2.setPassengerId(String.valueOf(passengerId));

					int q = orderPriceDetailMapper.insertSelective(detail1);
					int w = orderPriceDetailMapper.insertSelective(detail2);

					if (q != 1 || w != 1) {
						return new DataBean(400, new JSONObject(), "快车预估价订单详情插入失败哦!");
					}

				} else {
					return new DataBean(407, new JSONObject(), "缓存里面该乘客没有一口价,必须从先调用预估价接口再下拼车单!!!!");
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(405, new JSONObject(), "参数错误!");
		}

		User user = UserUtil.getUser(fields.getInt("passengerId"), fields.getString("token"));

		if (user == null) {
			return new DataBean(406, new JSONObject(), "乘客id或者token错误!");
		}
		// 2 为等待接单
		order.setOrderStatus(Constants.ORDER_WAITING);

		order.setPassengerPhone(user.getPhone());

		Integer i = orderMapper.insertSelective(order);
		if (i == 1) {
			// 创建订单后，写入野狗
			WilddogUtil.sendOrderToPassenger(order.getOrderNum(), orderService.sendToPassengerTemp(order));
			return new DataBean(200, order, "下单成功!");
		} else {
			return new DataBean(400, new JSONObject(), "下单失败!");
		}

	}

	public static void main(String[] args) {
		String string = Redis.c.get(Redis.K.CARPOOL_INFO.to(270));
		JSONObject fromObject = JSONObject.fromObject(string);
		double object = Double.valueOf(fromObject.get("spassRatePrice").toString());
		System.out.println(fromObject);
		System.out.println(object);
	}

	@Override
	public DataBean login(int passengerId) {

		List<Order> list = orderMapper.selectGoingOrderNum(passengerId);

		if (list.isEmpty()) {
			return new DataBean(400, new JSONObject(), "没有正在进行的快车单!");
		}

		Map<String, Object> map = new HashMap<>();

		// 判断是否有未支付订单,如果有就返回
		for (Order order : list) {
			Integer payStatus = order.getPayStatus();
			map.put("orderType", order.getOrderType());
			map.put("orderNum", order.getOrderNum());
			map.put("orderStatus", order.getOrderStatus());
			map.put("passengerId", order.getPassengerId());
			map.put("payStatus", payStatus);
			if (payStatus == 1) {
				return new DataBean(200, map, "调用成功返回未支付订单!");
			}
		}

		// 返回时间最近的未完成快车单
		long l = 0L;
		for (int i = 0; i < list.size(); i++) {
			Order order = list.get(i);
			if (i == 0) {
				l = order.getPlanTime().getTime();
			}
			if (order.getPlanTime().getTime() <= l) {
				l = order.getPlanTime().getTime();
				map.put("orderType", order.getOrderType());
				map.put("orderNum", order.getOrderNum());
				map.put("orderStatus", order.getOrderStatus());
				map.put("payStatus", order.getPayStatus());
				map.put("passengerId", order.getPassengerId());
			}
		}
		return new DataBean(200, map, "调用成功返回时间最近的快车单!");
	}

	@Override
	public DataBean createJSPOrder(JSONObject fields) {
		Order order = new Order();
		Date createTime = new Date(System.currentTimeMillis());
		order.setCreateTime(createTime);
		order.setStartTime(createTime);
		// 网约车生成的订单以20开头
		String orderNo = "20" + RandomUtil.getRandomDateAndNumber();

		try {
			int passengerId = fields.getInt("passengerId");
			// 判断乘客是否有未支付的订单
			int count1 = orderMapper.selectPayOrderCountByPassengerId(passengerId);
			if (count1 > 0) {
				return new DataBean(408, new JSONObject(), "乘客有未支付订单,请先完成支付后再下单!");
			}

			// 根据乘客id查询客户未完成的订单数
			List<Order> list = orderMapper.selectOrderCountByPassengerId(passengerId);
			int a = 0;
			if (!list.isEmpty()) {
				for (Order order1 : list) {
					long planTime1 = order1.getPlanTime().getTime();
					long createTime2 = order1.getCreateTime().getTime();

					if (planTime1 == createTime2) {
						return new DataBean(407, new JSONObject(), "乘客有正在进行的订单,不能重复下单!");
					}

					if (planTime1 != createTime2) {
						a++;
					}
					
					if (Constants.CARPOOL_NOW == order1.getOrderType() || Constants.CARPOOL_FU == order1.getOrderType()) {
						return new DataBean(407, new JSONObject(), "乘客有正在进行的接送机一口价订单,不能重复下单!");
					}
				}
			}

			String id = UuidUtils.getUUID();
			order.setId(id);
			order.setOrderNum(orderNo);

			int useSeats = fields.getInt("useSeats");
			order.setUseSeats(useSeats);

			// 七座车一口价
			String aprice = dictionaryService.selectByTheNode("0402").getRemark();
			Integer price = Integer.valueOf(aprice);
			double orderPrice = useSeats * price;
			order.setOrderPrice(orderPrice);

			int carType = fields.getInt("carType");
			order.setCarType(carType);

			// 乘车人姓名
			String customerName = fields.getString("customerName");
			if (StringUtil.isEmpty(customerName)) {
				customerName = null;
			}
			order.setCustomerName(customerName);

			// 乘车人电话
			String customerPhone = fields.getString("customerPhone");
			if (StringUtil.isEmpty(customerPhone)) {
				customerPhone = null;
			}
			order.setCustomerPhone(customerPhone);

			String startAddress = fields.getString("startAddress");
			if (StringUtil.isEmpty(startAddress)) {
				return new DataBean(10010, new JSONObject(), "起点地址不能为空,请返回选择!");
			}
			order.setStartAddress(startAddress);

			String startLocation = fields.getString("startLocation");
			if (StringUtil.isEmpty(startLocation)) {
				return new DataBean(10011, new JSONObject(), "起点经纬度不能为空,请返回选择!");
			}
			order.setStartLocation(startLocation);

			String desAddress = fields.getString("desAddress");
			if (StringUtil.isEmpty(desAddress)) {
				return new DataBean(10012, new JSONObject(), "终点地址不能为空,请返回选择!");
			}
			order.setDesAddress(desAddress);

			String desLocation = fields.getString("desLocation");
			if (StringUtil.isEmpty(desLocation)) {
				return new DataBean(10013, new JSONObject(), "终点经纬度不能为空,请返回选择!");
			}
			order.setDesLocation(desLocation);

			int pcType = fields.getInt("pcType");
			order.setPcType(pcType);

			String planTime = fields.getString("planTime");
			Long l = Long.valueOf(planTime);

			if (l <= createTime.getTime()) {
				order.setOrderType(Constants.CARPOOL_NOW);
				order.setPlanTime(createTime);
			} else {
				if (a > 0) {
					return new DataBean(407, new JSONObject(), "乘客不能多次下预约单!");
				}
				order.setOrderType(Constants.CARPOOL_FU);
				order.setPlanTime(new Date(l));
			}

			order.setPassengerId(passengerId);

		} catch (Exception e) {
			e.printStackTrace();
			return new DataBean(405, new JSONObject(), "参数错误!");
		}

		User user = UserUtil.getUser(fields.getInt("passengerId"), fields.getString("token"));

		if (user == null) {
			return new DataBean(406, new JSONObject(), "乘客id或者token错误!");
		}
		// 2 为等待接单
		order.setOrderStatus(Constants.ORDER_WAITING);

		order.setPassengerPhone(user.getPhone());

		Integer i = orderMapper.insertSelective(order);
		if (i == 1) {
			// 创建订单后，写入野狗
			WilddogUtil.sendOrderToPassenger(order.getOrderNum(), orderService.sendToPassengerTemp(order));
			return new DataBean(200, order, "下单成功!");
		} else {
			return new DataBean(400, new JSONObject(), "下单失败!");
		}

	}
}
